package com.iweb.dao;

import com.iweb.pojo.Strategy;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

public class StrategyDaoImpl implements StrategyDao {

    private Connection connection;

    public StrategyDaoImpl(Connection connection) {
        this.connection = connection;
    }

    @Override
    public List<Strategy> selectList(String title) throws Exception {
        List<Strategy> strategies = new ArrayList<>();
        String sql = "select * from tb_strategy ";
        if (title!=null){
            sql += "where strategy_title like ?";
        }
        PreparedStatement pst = connection.prepareStatement(sql);

        if (title!=null){
            pst.setObject(1,"%"+title+"%");
        }

        ResultSet rs = pst.executeQuery();

        Strategy strategy = null;
        while (rs.next()){
            strategy = createStrategy(rs);
            strategies.add(strategy);
        }
        return strategies;
    }

    private Strategy createStrategy(ResultSet rs) throws Exception {
        Strategy strategy = new Strategy();
        strategy.setId(rs.getString(1));
        strategy.setTitle(rs.getString(2));
        strategy.setDetail(rs.getString(3));
        strategy.setPath(rs.getString(4));
        strategy.setPath1(rs.getString(5));
        strategy.setPath2(rs.getString(6));
        return strategy;
    }
}
